package com.parkLot.spring.socket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

@Slf4j
@Component
public class SocketServerPoint {

	private static int port = 2021;
	private Socket socket = null;
	private static OutputStream espOs = null;
	
	//初始化服务器
	public SocketServerPoint(int serverPort) {
		port = serverPort;
	}
	
	public SocketServerPoint() {
		//port = serverPort;
		super();
	}
	
	//开启多线程监听
	public void startSocket() {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					ServerSocket serverSocket = new ServerSocket(port);
					log.info("ServerSocket创建成功！，当前目标端口："+port);
					log.info("服务器启动成功，等待连接~");

					Socket socket = null;
					while(true) {
						socket = serverSocket.accept();
						if(socket != null) {
							log.info("连接成功");
							InetAddress address = socket.getInetAddress();
							log.info("已连接上，主机IP："+address.getLocalHost()+"从机端口："+socket.getPort());
							clientRead(socket);
						}
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					System.out.println("ServerSocket服务启动失败，目标端口："+port);
				}
			}
		}).start();
	}

	//接收消息的方法
	private static void clientRead(Socket cs) {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {
			InputStream is = null;
			OutputStream os = null;
			
			
            @Override
            public void run() {
            	try {
            		if(cs != null) {
                		is = cs.getInputStream();
                		os = cs.getOutputStream();
                		espOs = os;
                	}
            		while(cs != null && cs.isConnected()) {
            			int buffer_length = is.available();
            			if (buffer_length > 0) {
            				byte[] bytes = new byte[buffer_length];
							if(is.read(bytes) == -1) {
								log.info("接受消息失败");
								cs.close();
							}
							String info = new String(bytes, 0, buffer_length, "UTF-8");
							log.info("收到消息："+info);

//							if(bytes[0] == 0x11) {
//								//�ڵ�����
//								String info = byteArrayToHexStr(bytes);
//								System.out.println("�ڵ���룺"+info.substring(2, 6));
//							}else if(bytes[0] == 0x22) {
//								//�ڵ����״̬
//								String info = byteArrayToHexStr(bytes);
//								System.out.println("������ɣ�"+info.substring(2, 6));
//							}else {
//								String info = byteArrayToHexStr(bytes);
//								System.out.println("δ֪������"+info);
//								//sendToESP8266("3eda2f");
//							}
						}
            		}
				} catch (Exception e) {
					// TODO: handle exception
				}
            } 
		}).start();
	}
		
	public SocketServerPoint(Socket socket) {
		super();
		this.socket = socket;
	}

	public void sendTO8266(String info) {
		try{
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(espOs));
			bw.write(info+"\n");
			bw.flush();
		}catch (Exception e){
			// TODO: 处理一些可能发生的异常
			log.info("数据发送异常");
		}
	}
	/*
	//如果使用十六进制进行数据收发的话，可以用下面的方法完成转化
	public void sendToESP8266(String info) {
		try {
			byte[] cmd = hexStrToByteArray(info);
			if(espOs != null) {
				espOs.write(cmd);
				espOs.flush();
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("����ʧ��");
		}
		
	}
	

	public static String byteArrayToHexStr(byte[] byteArray) {
        if (byteArray == null){
            return null;
        }
        char[] hexArray = "0123456789ABCDEF".toCharArray();
        char[] hexChars = new char[byteArray.length * 2];
        for (int j = 0; j < byteArray.length; j++) {
            int v = byteArray[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
	

	public static byte[] hexStrToByteArray(String str)
    {
        if (str == null) {
            return null;
        }
        if (str.length() == 0) {
            return new byte[0];
        }
        byte[] byteArray = new byte[str.length() / 2];
        for (int i = 0; i < byteArray.length; i++){
            String subStr = str.substring(2 * i, 2 * i + 2);
            byteArray[i] = ((byte)Integer.parseInt(subStr, 16));
        }
        return byteArray;
    }

	 */
}
